define(function(require) {

  var orderTable;
  var firstTime = true;

  //include
  require('./list-tpl');

  var listTpl = juicer.templates['list.juicer.html'];

  var List = {
    init: function() {

      this.initOrderTable();
      this.iniQuerytValidator();
      this.bindEvent();

    },
    /**
     * 表单验证初始化
     */
    iniQuerytValidator: function() {

      var fields = {
        serarch_value: {
          validators: {
            message: '电话输入错误',
            phone: {
              country: 'CN',
              message: '请输入正确的电话格式'
            },
            callback: {
              message: '请输入号码',
              callback: function(value, validator) {
                if (!value) {
                  return false;
                } else {
                  return true;
                }
              }
            }
          }
        }
      }
      $('#query_error_form').bootstrapValidator({
        message: '输入错误',
        feedbackIcons: {
          valid: 'glyphicon glyphicon-ok',
          invalid: 'glyphicon glyphicon-remove',
          validating: 'glyphicon glyphicon-refresh'
        },
        fields: fields
      });
    },
    /**
     * 初始化订单的列表
     */
    initOrderTable: function() {
      orderTable = $("#order_error_table").dataTable({
        "oLanguage": CRM.pageConfig,
        "sScrollX": "100%", //表格的宽度
        "sScrollXInner": "100%", //表格的内容宽度
        "bScrollCollapse": true, //当显示的数据不足以支撑表格的默认的高度时，依然显示纵向的滚动条。(默认是false)
        "bPaginate": true, //是否显示分页
        "bLengthChange": true, //每页显示的记录数
        "bFilter": false, //搜索栏
        "bSort": false, //是否支持排序功能
        "bInfo": false, //显示表格信息
        "bAutoWidth": false, //自适应宽度
        "bServerSide": true, //开启服务端处理
        "sAjaxSource": CRM.getOuterUrl('/outway/errorOrder/queryList'),
        "fnInitComplete": function() {
          this.fnAdjustColumnSizing(true);
        },
        "fnServerData": function(sSource, aoData, fnCallback) {
          if (firstTime) {
            firstTime = false;
            return;
          }
          var searchType = $("#search_error_type").val(),
              searchVal = $("#serarch_error_value").val(),
              searchVal = $.trim(searchVal);
              searchJson = (searchType == 'mobile' ? 
                {"receiverMobile": searchVal} : 
                {"buyerMobile": searchVal}
              );

          var data = $.extend({
            "pageNum": aoData[3].value / aoData[4].value + 1,
            "pageSize": aoData[4].value,

          }, searchJson);
          $.ajax({
            "type": 'POST',
            "url": sSource,
            "dataType": "json",
            xhrFields: {
              withCredentials: true
            },
            "data": data,
            "success": function(req) {
              if (req.status == false && req.responseCode == 10212) {
                var loc = location.href;
                location.href = CRM.getOuterUrl('/member/login.html?redirectUrl=' + encodeURIComponent(loc));
              } else if (req.responseCode && req.status) {
                var resultData = CRM.getDataTabelDtaObject();
                if (req.entry) {
                  resultData.iTotalDisplayRecords = 9999;
                  resultData.iTotalRecords = 9999;
                  for (var length in req.entry) {
                    eval('req.entry[length].attributes=' + req.entry[length].attributes);
                    if (!req.entry[length].attributes) {
                      req.entry[length].attributes = "";
                    }
                    resultData.aaData.push([req.entry[length]]);
                  }
                }
              } else {
                $("#msg_dialog_content").text(req.message);
                $('#msg_dialog').modal('show');
              }
              fnCallback(resultData);
            },
            error: function(e) {
              //请求出错处理
              $("#msg_dialog_content").text("订单列表,请求服务异常！");
              $('#msg_dialog').modal('show');
            }
          });
        },
        "aoColumns": [{
            "bSortable": false,
            "mRender": function(data, type, row) {
              return renderOrderListMain(data);
            }
          }

        ], //列设置，表有几列，数组就有几项
        "bStateSave": true, //保存状态到cookie *************** 很重要 ， 当搜索的时候页面一刷新会导致搜索的消失。使用这个属性就可避免了
        "sPaginationType": "simple" //分页，一共两种样式，full_numbers和two_button(默认)

      });
    },
    searchList: function() {
      $("#query_error_form").data('bootstrapValidator').resetForm();
      $("#query_error_form").data('bootstrapValidator').validate();
      if ($("#query_error_form").data('bootstrapValidator').isValid()) {
          $('#order_error_table').DataTable().ajax.reload();
      }
    },
    bindEvent: function() {
      var self = this;
      var elSearch = $("#search_error_btn")
      elSearch.on('click', function() {
        $('#order_error_table_wrap').show();
        $('#order_table_wrap').hide();
        self.searchList();
      });

      $("#search_error_type").on('change', function() {
        $("#serarch_error_value").attr("placeholder", $("#search_error_type").find("option:selected").text());
      });
    }
  };


  /**
   * 渲染订单列表主信息
   * @param data
   */
  function renderOrderListMain(data) {

    if (data) {
      var html = listTpl({
        data: data
      });
      return html;
    }

  }

  return List;
});